import Data.List (transpose)
import Utils (tok, (&&&))

countMismatchesAt :: Eq a => Int -> [a] -> Int
countMismatchesAt i xs = length
                       . filter (uncurry (/=))
                       $ zip (reverse left) right
    where
        (left, right) = (take i xs, drop i xs)

solveBlock :: Eq a => ([[a]] -> Int) -> [[a]] -> Int
solveBlock f = uncurry (+) . (&&&) f ((*100) . f . transpose)

findSymmCol :: Eq a => [[a]] -> Int
findSymmCol ls = 
    go 1
    where
        go i
            | i == (length ls!!0)                      = 0
            | all (==0) $ map (countMismatchesAt i) ls = i
            | otherwise                                = go (i + 1)

findSymmCo2 :: Eq a => [[a]] -> Int
findSymmCo2 ls = 
    go 1
    where
        go i
            | i == (length (ls!!0)) = 0
            | found                 = i
            | otherwise             = go (i + 1)
            where
                found = length (filter (==1) nbsMism) == 1
                     && length (filter (==0) nbsMism) == length nbsMism - 1
                nbsMism = map (countMismatchesAt i) ls

main = do
    contents <- readFile "input.txt"

    let blocks = tok [""] . lines $ contents

    print $ sum . map (solveBlock findSymmCol) $ blocks

    print $ sum . map (solveBlock findSymmCo2) $ blocks

    